package com.zjpavt.client.util;

import com.zjpavt.client.page.PageManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @program: PavtFirmware
 * @description:
 * @author: zyc
 * @create: 2018-06-13 15:17
 **/
public class StringUtil {
    static Logger log = LoggerFactory.getLogger(StringUtil.class);

    private static final char CHAR_0 = '0';
    private static final char CHAR_1 = '1';

    /**
     * Returns true if a and b are equal, including if they are both null.
     * <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if
     * both the arguments were instances of String.</i></p>
     * @param a first CharSequence to check
     * @param b second CharSequence to check
     * @return true if a and b are equal
     */
    public static boolean equals(CharSequence a, CharSequence b) {
        if (a == b) {
            return true;
        }
        int length;
        if (a != null && b != null && (length = a.length()) == b.length()) {
            if (a instanceof String && b instanceof String) {
                return a.equals(b);
            } else {
                for (int i = 0; i < length; i++) {
                    if (a.charAt(i) != b.charAt(i)) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }


    /**
     * @param str String 数组
     * @return 只要有一个为空或者为空字符串就返回true ，全部通过返回false。
     */
    public static boolean isNullOrEmpty(String... str) {
        for (String s : str) {
            if (s == null || s.isEmpty()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 字符串的数字数组转化成int数组
     * @param command
     * @return
     */
    public static int[] commandStr2Int(String command) {
        char[] chars = command.toCharArray();
        int[] result = new int[chars.length];
        for (int i = 0; i < result.length; i++) {
            result[i] = Character.getNumericValue(chars[i]);
        }
        return result;
    }

    public static String commandInt2String(int[] command) {
        StringBuilder sb = new StringBuilder();
        for (int i : command) {
            sb.append(i);
        }
        return sb.toString();
    }

    /**
     * 注意如果不是个位数数组 可能会出现问题
     * @param command
     * @return
     */
    public static String commandInt2String(byte[] command) {
        StringBuilder sb = new StringBuilder();
        for (int i : command) {
            sb.append(i);
        }
        return sb.toString();
    }


    public static byte[] decodeCommand(String command) throws IllegalArgumentException {
        return decodeHex(command.replace(PageManager.SPACE_FILL_1, "").toCharArray());
    }


    /**
     * 十六进制字符数组转字节数组
     *
     * @param data 十六进制char[]
     * @return byte[]
     * @throws IllegalArgumentException
     */
    public static byte[] decodeHex(char[] data) throws IllegalArgumentException {
        int len = data.length;
        if ((len & 0x01) != 0) {
            throw new IllegalArgumentException("Odd number of characters.");
        }
        byte[] out = new byte[len >> 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f = f | toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }
        return out;
    }


    /**
     * 十六进制字符转整数
     *
     * @param ch    十六进制char
     * @param index 十六进制字符在字符数组中的位置
     * @return 一个整数
     * @throws IllegalArgumentException
     */
    private static int toDigit(char ch, int index) throws IllegalArgumentException {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new IllegalArgumentException("illegal hexadecimal character " + ch
                                               + " at index " + index);
        }
        return digit;
    }

    /**
     * 二进制字符串转十六进制字符串
     *
     * @param binary   二进制字符串
     * @param hex        十六进制字符串
     * @return 一个整数
     * @throws IllegalArgumentException
     */
    private static final int BIN2HEX_LENGTH = 4;

    public static String bin2Hex(String binary) throws IllegalArgumentException {
        if (isNullOrEmpty(binary)) {
            throw new IllegalArgumentException("illegal binary string is empty or null!" + binary);
        }
        if (binary.length() % BIN2HEX_LENGTH != 0) {
            throw new IllegalArgumentException("illegal binary string " + binary
                                               + " length is not multiple of 4");
        }
        StringBuilder stringBuilder = new StringBuilder();
        int indexInBinary = 0;
        while (indexInBinary != binary.length()) {
            char[] oneHexChar = new char[BIN2HEX_LENGTH];
            binary.getChars(indexInBinary, indexInBinary + BIN2HEX_LENGTH, oneHexChar, 0);
            int num = 0;
            for (int i = 0; i < BIN2HEX_LENGTH; i++) {
                if (oneHexChar[i] == CHAR_1) {
                    num += Math.pow(2, 3 - i);
                } else if (oneHexChar[i] != CHAR_0) {
                    throw new IllegalArgumentException("with char that is not 0 or 1 in the binary:" + binary);
                }
            }
            if (num >= 0 && num < 10) {
                stringBuilder.append(num);
            } else if (num >= 10 && num < 16) {
                stringBuilder.append((char) ('a' + num - 10));
            } else {
                throw new IllegalArgumentException("i think it will be never be Exception!");
            }
            indexInBinary += 4;
        }
        return stringBuilder.toString();
    }

    /**
     *  如果是十六进制数 直接转化，如果不是十六进制 且 is2Hex == false 则会在下一层报异常
     *  如果is2Hex == true 则会末尾补0
     * @param binary	二进制数据
     * @param is2Hex 末尾补0
     * @return
     * @throws IllegalArgumentException
     */
    public static String bin2Hex(String binary,boolean is2Hex) throws IllegalArgumentException {
        int mod = binary.length() % 4;
        if (is2Hex && mod !=0) {
            int appendLength = 4 - mod;
            StringBuilder stringBuilder = new StringBuilder(binary);
            while (appendLength != 0) {
                stringBuilder.append(CHAR_0);
                appendLength--;
            }
            return bin2Hex(stringBuilder.toString());
        } else {
            return bin2Hex(binary);
        }
    }
    /**
     * @param command 指令
     * @param index 保留指令的位数
     * */
    public static String formatCommand(String command,int index) {
        int length=command.length();
        log.debug("command length :"+length);
        if (index > length) {
            log.debug("command length :"+length + "shorter than need length");
            return command;
        }
        return  command.substring(0,index);
    }

    /**
     * uuid转化为不带参数的字符串
     * @param uuid 不接受null参数
     * @return
     */
    public static String uuid2Str(UUID uuid) {
        return uuid.toString().replaceAll("-", "");
    }

    /**
     * 如果字符为空或者null 则使用默认值
     * @param checkString
     * @param defaultString
     * @return
     */
    public static String checkStringNotEmptyAndNull(String checkString, String defaultString) {
        if (StringUtil.isNullOrEmpty(checkString)) {
            checkString = defaultString;
        }
        return checkString;
    }
}
